package com.github.postsanf.yinian.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.github.postsanf.yinian.ElseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.huanxin.DemoHelper;
import com.github.postsanf.yinian.service.DemoPushService;
import com.github.postsanf.yinian.service.StatisticsService;
import com.github.postsanf.yinian.utils.DoSecretUtils;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.igexin.sdk.PushManager;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 启动页
 */
public class SplashActivity2 extends ElseActivity {
    private static final String[] mouthlist = new String[]{"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
    private static final int WHAT_INTENT2MAIN = 2;
    private static final int WHAT_INTENT2LOGINCHOOSE = 4;
    private static final int WHAT_ANIMATION1 = 5;
    private static final int WHAT_ANIMATION2 = 6;
    private static final int WHAT_ANIMATION3 = 7;
    private static final int WHAT_ANIMATION4 = 8;
    private static final int WHAT_LOGIN = 10;
    private SharedPreferences sp_login;
    private IWXAPI wxApi;
    private TextView iv_splash_start1;
    private ImageView iv_splash_start2;
    private ImageView iv_splash_start2_qg;
    private ImageView iv_splash_start3;
    private ImageView iv_splash_skip;
    private LinearLayout iv_splash_start4;
    private TextView splash_day;
    private TextView splash_mouth;
    private TextView splash_year;
//    private RelativeLayout mLocalBlurRootView;
    private String uuid;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_INTENT2LOGINCHOOSE:
                    final boolean splashGuide = SpUtils.getBoolean(SplashActivity2.this, "welcomeGuide");
                    if (splashGuide) {
                        intent2Activity(LoginActivity.class);
                        intent2Activity(LoginWeChatActivity.class);
                        finish();
                    } else {
                        SpUtils.put(SplashActivity2.this, "welcomeGuidestart", false);
                        startActivity(new Intent(SplashActivity2.this, WelcomeActivity.class));
                        finish();
                    }
                    break;
                case WHAT_INTENT2MAIN:
                    intent2Activity(MainActivity.class);
                    boolean bb = getSharedPreferences(ACTIONs.mypassword, 0).getBoolean(ACTIONs.numcodepasswordbb, false);
                    if (bb) {
                        intent2Activity(YNCodeLockActivity.class);
                    }
                    finish();
                    break;
                case WHAT_ANIMATION1:
                    iv_splash_start1.setVisibility(View.VISIBLE);
                    ObjectAnimator start1 = ObjectAnimator.ofFloat(iv_splash_start1, "alpha", 0.0f, 1.0f);
                    start1.setDuration(1370);
                    start1.setRepeatCount(0);
                    start1.start();
                    break;
                case WHAT_ANIMATION2:
                    iv_splash_start2.setVisibility(View.VISIBLE);
                    iv_splash_start2_qg.setVisibility(View.VISIBLE);
                    ObjectAnimator start2 = ObjectAnimator.ofFloat(iv_splash_start2, "alpha", 0.0f, 1.0f);
                    start2.setDuration(640);
                    start2.setRepeatCount(0);
                    start2.start();
                    ObjectAnimator start2qg = ObjectAnimator.ofFloat(iv_splash_start2_qg, "alpha", 0.0f, 1.0f);
                    start2qg.setDuration(640);
                    start2qg.setRepeatCount(0);
                    start2qg.start();
                    ObjectAnimator scaleX = ObjectAnimator.ofFloat(iv_splash_start2, "scaleX", 1.0f, 1.05f);
                    ObjectAnimator scaleY = ObjectAnimator.ofFloat(iv_splash_start2, "scaleY", 1.0f, 1.05f);
                    AnimatorSet animatorSet = new AnimatorSet();
                    animatorSet.playTogether(scaleX, scaleY);
                    animatorSet.setDuration(4000);
                    animatorSet.start();
                    break;
                case WHAT_ANIMATION3:
                    iv_splash_start3.setVisibility(View.VISIBLE);
                    ObjectAnimator ta3 = ObjectAnimator.ofFloat(iv_splash_start3, "translationY", 0, -27);
                    ta3.setDuration(4000);
                    ta3.setRepeatCount(0);
                    ta3.start();
                    break;
                case WHAT_ANIMATION4:
//                    ViewTreeObserver vto = iv_splash_start4.getViewTreeObserver();
//                    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//
//                        @Override
//                        public void onGlobalLayout() {
//                            mLocalBlurRootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//                            BlurBitmapUtil.blur(mLocalBlurRootView, iv_splash_start4, 5, 8);
//                        }
//                    });
                    iv_splash_skip.setVisibility(View.VISIBLE);
                    iv_splash_start4.setVisibility(View.VISIBLE);
                    ObjectAnimator start4 = ObjectAnimator.ofFloat(iv_splash_start4, "alpha", 0.0f, 1.0f);
                    start4.setDuration(130);
                    start4.setRepeatCount(0);
                    start4.start();
                    ObjectAnimator ta4 = ObjectAnimator.ofFloat(iv_splash_start4, "translationY", 0, -29);
                    ta4.setDuration(2960);
                    ta4.setRepeatCount(0);
                    ta4.start();
                    break;
                case WHAT_LOGIN:
                    // 新用户
                    if (StringUtils.isEmptyString(uuid) || !DemoHelper.getInstance().isLoggedIn()) {
                        handler.sendEmptyMessage(WHAT_INTENT2LOGINCHOOSE);
                    } else {
                        application.setCurID(Integer.parseInt(uuid));
                        handler.sendEmptyMessage(WHAT_INTENT2MAIN);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        regToWx();
        setContentView(R.layout.yn_activity_splash2);
        sp_login = application.getSp_login();
        uuid = DoSecretUtils.getSecretStr(sp_login.getString(getString(R.string.LID), ""));
        //埋点
        statistics();
        //动画
        initAnimation();
        handler.sendEmptyMessageDelayed(WHAT_LOGIN, 4000);
        SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean("active", false);
        ed.commit();
        //经过Splash界面表示程序退出后从新进入
        SharedPreferences spImport = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = spImport.edit();
        edit.putBoolean("exit", true);
        edit.commit();
        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
    }

    private void statistics() {
        Long time = SpUtils.getLong(SplashActivity2.this, "time");
        toJson(time);
        //继续上传上次上传失败的数据
        String failJson = SpUtils.getString(SplashActivity2.this, "failJson");
        if (failJson.startsWith("{")) {
            Intent intent = new Intent(SplashActivity2.this, StatisticsService.class);
            intent.setAction(ACTIONs.failJson);
            intent.putExtra("failJson", failJson);
            startService(intent);
//            SpUtils.put(SplashActivity.this,"failJson",null);
        }
    }

    private void toJson(Long time) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject jsonObject9 = new JSONObject();
            JSONObject jsonObject10 = new JSONObject();
            JSONObject jsonObject11 = new JSONObject();
            JSONObject jsonObject12 = new JSONObject();
            jsonObject9.put("totalTime", time);
            jsonObject10.put("data", jsonObject9);
            jsonObject10.put("type", 1);
            jsonArray.put(jsonObject10);
            jsonObject11.put("startCount", 1);
            jsonObject12.put("data", jsonObject11);
            jsonObject12.put("type", 2);
            jsonArray.put(jsonObject12);
            jsonObject.put("userid", application.getCurID());
            jsonObject.put("version", getVersion());
            jsonObject.put("device", "Android");
            jsonObject.put("totalData", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(SplashActivity2.this, StatisticsService.class);
        intent.setAction(ACTIONs.uploadRecode);
        intent.putExtra("json", jsonObject.toString());
        startService(intent);
    }

    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void initAnimation() {
        iv_splash_start1 = ((TextView) findViewById(R.id.iv_splash_start1));
        iv_splash_start2 = ((ImageView) findViewById(R.id.iv_splash_start2));
        iv_splash_start2_qg = ((ImageView) findViewById(R.id.iv_splash_start2_qg));
        iv_splash_start3 = ((ImageView) findViewById(R.id.iv_splash_start3));
        iv_splash_skip = ((ImageView) findViewById(R.id.iv_splash_skip));
        iv_splash_start4 = ((LinearLayout) findViewById(R.id.iv_splash_start4));
        splash_day = ((TextView) findViewById(R.id.splash_day));
        splash_mouth = ((TextView) findViewById(R.id.splash_mouth));
        splash_year = ((TextView) findViewById(R.id.splash_year));
//        mLocalBlurRootView = (RelativeLayout) findViewById(R.id.local_blur_root);
        String localPath = "";
        String strday = new SimpleDateFormat("yyyy-MM-dd").format(new Date(new Date().getTime()));
        String tommorw = new SimpleDateFormat("yyyy-MM-dd").format(new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
        String Text = "";
        if (strday.equals(SpUtils.getString(SplashActivity2.this, "newtodayDate"))) {
            Text = SpUtils.getString(SplashActivity2.this, "newtodayText");
            localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.yiniantodayshow/" + strday + ".jpg";
            if (new File(localPath).exists()) {
                Glide.with(SplashActivity2.this).load("file:///" + localPath).into(iv_splash_start2);
            }
        } else if (strday.equals(SpUtils.getString(SplashActivity2.this, "newTomorrowDate"))) {
            Text = SpUtils.getString(SplashActivity2.this, "newTomorrowText");
            localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.yiniantodayshow/" + tommorw + ".jpg";
            if (new File(localPath).exists()) {
                Glide.with(SplashActivity2.this).load("file:///" + localPath).into(iv_splash_start2);
            }
        }
        iv_splash_start1.setTypeface(Typeface.createFromAsset(getAssets(), "MFKeSong-Regular.ttf"));
//        try {
//            JChineseConvertor jChineseConvertor = JChineseConvertor
//                    .getInstance();
        String s = "我遇见你，我记得你，这座城市天生就适合谈恋爱，你天生就适合我的灵魂";
//            iv_splash_start1.setText(jChineseConvertor.s2t(s));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        if (!StringUtils.isEmpty(Text)) {
            iv_splash_start1.setText(Text);
        } else {
            iv_splash_start1.setText(s);
        }
        splash_day.setTypeface(Typeface.createFromAsset(getAssets(), "splash_day.ttf"));
        splash_year.setTypeface(Typeface.createFromAsset(getAssets(), "splash_day.ttf"));
        splash_mouth.setTypeface(Typeface.createFromAsset(getAssets(), "splash_mouth.ttf"));
        Date mdate = new Date(System.currentTimeMillis());
        String str = new SimpleDateFormat("yyyy-MM-dd").format(mdate);
        splash_year.setText(str.split("-")[0]);
        splash_mouth.setText(mouthlist[mdate.getMonth()]);
        splash_day.setText(str.split("-")[2]);
        Glide.with(SplashActivity2.this).load(R.drawable.iv_splash_skip).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(iv_splash_skip);
        iv_splash_skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmptyString(uuid) || !DemoHelper.getInstance().isLoggedIn()) {
                    handler.sendEmptyMessage(WHAT_INTENT2LOGINCHOOSE);
                } else {
                    application.setCurID(Integer.parseInt(uuid));
                    handler.sendEmptyMessage(WHAT_INTENT2MAIN);
                }
            }
        });
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION1, 0);
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION2, 330);
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION3, 330);
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION4, 1340);
    }

    private void regToWx() {
        wxApi = WXAPIFactory.createWXAPI(this, getString(R.string.WX_APP_ID));
        wxApi.registerApp(getString(R.string.WX_APP_ID));
        application.setWxApi(wxApi);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
